


import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:moonplay/common/app_common.dart';
import 'package:moonplay/model/source_model.dart';
import 'package:moonplay/pages/common_page/common_text_page.dart';
import 'package:moonplay/utils/loading.dart';
import 'package:webview_flutter/webview_flutter.dart';

class CommonWebviewPage extends StatefulWidget {
  @override
  _CommonWebviewPageState createState() => _CommonWebviewPageState();
}

class _CommonWebviewPageState extends State<CommonWebviewPage> {
  Future _futureBuilderFuture;
  String playUrl;
  bool screenStatus = false;
  double rowHeight = 300.0;
  SourceModel sourceModel;
  List sourceList = [];
  int sourceIndex = 0;
  bool isShow = true;
  WebViewController _webViewController;
  String vipUrl;

  @override
  void initState() {
    super.initState();
    vipUrl = Get.arguments['videoSetUrl'];
    print(vipUrl);
    init();
  }

  @override
  void dispose() {
    SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);//恢复
    SystemChrome.setPreferredOrientations([
      DeviceOrientation.portraitUp,
    ]);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: commonFutureBuilder(
        context,
        future: _futureBuilderFuture,
        callWidget: sourceModel != null ? bodyWidget() : Container(),
        callTap: init
      )
    );
  }

  Widget bodyWidget(){
    return Stack(
      children: [
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          bottom: !screenStatus ? ScreenUtil().getWidthPx(rowHeight) : 0,
          child: Visibility(
            child: webWidget(),
            maintainSize: true, 
            maintainAnimation: true,
            maintainState: true,
            visible: isShow
          ),
        ),
        Positioned(
          right: 0,
          bottom: !screenStatus ? ScreenUtil().getWidthPx(rowHeight) : 0,
          child: InkResponse(
            onTap: (){
              fullScreenFun();
            },
            child: Container(
              width: ScreenUtil().getWidthPx(100),
              height: ScreenUtil().getWidthPx(140),
              color: Colors.transparent,
            ),
          ),
        ),
        !screenStatus
        ? Positioned(
          left: 0,
          right: 0,
          bottom: 0,
          child: Container(
            width: double.infinity,
            height: ScreenUtil().getWidthPx(rowHeight),
            padding: EdgeInsets.symmetric(horizontal: ScreenUtil().getWidthPx(20)),
            child: GridView.builder(
              itemCount: sourceList.length,
              //SliverGridDelegateWithFixedCrossAxisCount 构建一个横轴固定数量Widget
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                //横轴元素个数
                crossAxisCount: 5,
                //纵轴间距
                mainAxisSpacing: 4.0,
                //横轴间距
                crossAxisSpacing: 4.0,
                //子组件宽高长度比例
                childAspectRatio: 1.5
              ),
              itemBuilder: (BuildContext context, int index) {
                return InkResponse(
                  onTap: () async {
                    // _webViewController.clearCache();
                    LogUtil.e("接收参数: ${vipUrl}");
                    setState(() {
                      isShow = false;
                      sourceIndex = index;
                      playUrl = sourceList[sourceIndex];
                    });
                    _webViewController.loadUrl(playUrl + vipUrl);
                    Loading.before('webview', "解析中...");
                    await Future.delayed(Duration(milliseconds: 3000));
                    setState(() {
                      isShow = true;
                    });
                    Loading.complete('webview');
                  },
                  child: Container(
                    decoration: BoxDecoration(
                      color: sourceIndex == index ? Color(0xffff426e) : Color(0xfff5f8f8),
                      borderRadius: BorderRadius.all(Radius.circular(4))
                    ),
                    alignment: Alignment.center,
                    child: Cmtext('解析${index+1}', style: TextStyle(fontSize: 13, color: sourceIndex == index ? Color(0xffffffff) : Color(0xff333333)),),
                  ),
                );
              }
            ),
          )
        )
        : Container(),
      ],
    );
  }

  Widget webWidget(){
    return WebView(
      initialUrl: playUrl + vipUrl,
      javascriptMode: JavascriptMode.unrestricted,
      onWebViewCreated: (WebViewController webViewController) {
        if (webViewController != null) {
          _webViewController = webViewController;
        }
      },
    );
  }

  fullScreenFun(){
    if (!screenStatus) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.landscapeLeft,
        DeviceOrientation.landscapeLeft,
      ]);
    } else {
      SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);//恢复
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
      ]);
    }
    setState(() {
      screenStatus = !screenStatus;
    });
  }

  //网络初始化
  init(){
    setState(() {
      _futureBuilderFuture = initGetIndex(Get.arguments['vodId']);
    });
  }

  //请求集数列表
  initGetIndex(vodId) async {
    Map<String, dynamic> postData = {};
    var _res = await HttpUtil().request("getListSource", data: postData, need_login: false);
    if(_res != null && _res['code'] == 200) {
      setState(() {
        sourceModel = SourceModel.fromJson(_res['data']);
        sourceList = sourceModel.records[0].source.split(",");
        playUrl = sourceList[sourceIndex];
      });
    }
    return _res;
  }
}